const router = require('koa-router')()
const svgCaptcha = require('svg-captcha')
const jwt = require('jsonwebtoken');
const fs = require('fs');
const path = require('path');
var image = require("imageinfo");
// var mimeType = require('mimeType')

const myKey = 'CYJMWXK';
let imgList = [];

const usermessage = [{
  'username':'yuanxiaoli',
  'userpsd':123456
}];
let num;

router.get('/yanma', async (ctx, next) => {
  let captcha = svgCaptcha.create({
    height: 36, // 下面都是配置项,详细可看官网
    fontSize: 40,
    color: false,
    ignoreChars: '0oO1iIl',
    noise: 1
  })
  // console.log(captcha)
  ctx.body = captcha;
  num = captcha.text;

})

router.get('/getcount', async (ctx, next) => {
  // console.log(captcha)
  ctx.body = imgList.length;

})

router.post('/deleteimg',async(ctx,next)=>{
  let name = ctx.request.body.name ;
  // console.log(name);
  let filePath1 = path.join(__dirname, 'images/') + `${name}`;
  // console.log(filePath1);
  fs.unlinkSync(filePath1)
  ctx.body={
    msg: '删除文件成功！'
  }
  // console.log(name);
  // ctx.body='ok';
})

router.post('/login', async (ctx, next) => {
  const content = ctx.request.body;
  console.log(content);
  usermessage.map((index)=>{
    console.log(index);
    if(index.username == content.username && index.userpsd == content.userpwd && num == content.yanma){
      let token = jwt.sign({"userName":content.username},myKey);
      // // console.log(token);
      ctx.body = {token:token,status:'ok'};
      // ctx.body='ok';
    }
  }) 
})

router.post('/uploadimg', async (ctx, next) => {
  let file = ctx.request.files.file;
  let token = ctx.request.headers.authorization;
  // console.log(token);
  let result = jwt.verify(token,myKey);
  // console.log(result);
  if(result.userName){
    // console.log(file);
    const reader = fs.createReadStream(file.filepath);
    let filename = file.originalFilename;
    // console.log(filename);
    let filePath = path.join(__dirname, 'images/') + `${filename}`;
    // console.log(filePath);
    let upStream = fs.createWriteStream(filePath);
    reader.pipe(upStream);
    ctx.body = {'status':'success'};
  }
})

router.post('/getimg',async(ctx,next)=>{
  imgList = [];
  let page = ctx.request.body.page;
  let listPath = path.join(__dirname, './images/') ;
  var files = fs.readdirSync(listPath);
  files.forEach(function (itm, index) {
    var stat = fs.statSync(listPath + itm);
    var ms = image(fs.readFileSync(listPath + itm));  
    var obj = {};//定义一个对象存放文件的路径和名字
    obj.path = 'http://localhost:3000/'+itm;//路径
    obj.filename = itm;//名字
    obj.filesize = stat.size;
    obj.filetype = ms.mimeType;
    imgList.push(obj);
  })
  console.log(imgList.length);
  if(imgList.length>=10*(page-1)){
    var newList = imgList.slice(10*(page-1),10*page);
    console.log(newList);
    ctx.body = newList;
  }else{
    ctx.body = [];
  }
})

module.exports = router
